<script>
import {ref,h,inject, onMounted} from "vue";
import {NIcon,NButton,NText} from "naive-ui";
import {BookmarkOutline, CaretDownOutline} from "@vicons/ionicons5";
import {getUserByUsername, updateUserCard} from "@/res/api/user_api.js";

export default defineComponent({
      name: "preference-util",
      props:{

      },
      setup(props){
        const { dark } = inject('dark')
        const { closeModelClick } = inject('closeModelClick')
        let optionKey = ref("preference")
        const menuOptions = [
          {
            label: () => h(
                NButton,
                {
                  text: true,
                  type: 'info',
                  onClick: ()=>{
                    optionKey.value = "preference"
                  }
                },
                { default: ()=>"个人资料" }
            ),
            key: "preference",
          },
          {
            label: () => h(
                NButton,
                {
                  text: true,
                  onClick: ()=>{
                    optionKey.value = "privacy"
                  }
                },
                { default: ()=>"隐私设置" }
            ),
            key: "privacy",
          },
          {
            label: () => h(
                NButton,
                {
                  text: true,
                  onClick: ()=>{
                    optionKey.value = "settings"
                  }
                },
                {
                  default: ()=>"通用设置"
                }
            ),
            key: "settings",
          },
        ];
        //主题菜单选项设置
        const generalOptions = ['系统', '深色', '浅色'].map(
            (v) => ({
              label: v,
              value: v
            })
        )
        let generalKey = ref("系统")
        function showSwitchCard(active){
          return optionKey.value === active
        }
        function changeOptionKey(changeVal){
          optionKey.value = changeVal
        }
        watch(generalKey,(newVal)=>{
          if (newVal === "浅色"){
            dark()
          }else if(newVal === "深色"){
            dark(true)
          }else {
            dark()
          }
        })
        //注销账户系列操作
        //弹出注销提示框
        function promptCancelClick() {
          $dialog.error({
            title: "注销账户",
            content: "确定要注销账户吗？",
            positiveText: "确定",
            negativeText: "不确定",
            onPositiveClick: () => {
              //注销成功操作
              $message.success("注销成功");
            }
          })
        }
        //计算器操作
        let timeing=60
        let textBtn = "发送验证码"
        let runTimeId = setTimeout(()=>{
        },1000)

        // 表单设置
        const formRef = ref(null);
        let modelRef = ref({
          username: "",
          sex: null,
          birthday: null,
          signature: "",
          userImg: null
        });
        const rules = {
          sex: [
            {
              required: true,
              message: "不可以为空喔~",
              trigger: ["input", "blur"]
            }
          ],
          birthday: [
            {
              required: true,
              message: "不可以为空喔~",
              type: "date",
              trigger: ["input", "blur"]
            }
          ],
          username: [
            {
              required: true,
              message: "不可以为空喔~",
              trigger: ["input", "blur"]
            }
          ],
          signature: [
            {
              required: true,
              message: "不可以为空喔~",
              trigger: ["input", "blur"],
            }
          ]
        }
        // 获取用户信息
        getUserByUsername().then((res) => {
          console.log(res.data)
          modelRef.value.username = res.data.nickname
          modelRef.value.birthday = res.data.birthday
          switch (res.data.sex) {
            case 1:
              modelRef.value.sex = "男"
              break
            case 2:
              modelRef.value.sex = "女"
              break
            default:
              modelRef.value.sex = "保密"
              break
          }
          modelRef.value.signature = res.data.signature
          modelRef.value.userImg = res.data.imgUrlIcon
        }).catch((err) => {
          $message.error(err.message)
        })
        // 修改用户信息
        const formData = new FormData();
        //图片上传
        const customRequest = ({
                                 file,
                                 data,
                                 headers,
                                 withCredentials,
                                 action,
                               })=>{
          if (data) {
            Object.keys(data).forEach((key) => {
              formData.append(
                  key,
                  data[key]
              );
            });
          }
          formData.append("file", file.file);
        }


        function userCardClick(e){
          e.preventDefault();
          formRef.value?.validate((errors) => {
            if (!errors){
              let sex = ref(null);
              sex.value = modelRef.value.sex;
              switch (sex.value){
                case "男":
                  sex.value = 1;
                  break
                case "女":
                  sex.value = 2;
                  break
                default:
                  sex.value = 0;
                  break
              }
              console.log(formData.get("file"))
              updateUserCard({
                nickname: modelRef.value.username,
                birthday: modelRef.value.birthday,
                sex: sex.value,
                signature: modelRef.value.signature,
                file: formData.get("file")
                  }).then((res) => {
                    window.location.reload()
                    $message.success("修改成功")
                    closeModelClick(true)
              }).catch((err) =>{
                $message.error(err.message)
              })
            } else {
              $message.destroyAll()
              $message.error("校验识别，请检测账户名/密码是否正确");
            }
          })
        }

        return {
          formRef,
          rules,
          customRequest,
          userCardClick,
          formValue: modelRef,
          collapsed: ref(true),
          menuOptions,showSwitchCard,optionKey,changeOptionKey,
          handleClose() {
            closeModelClick(false)
          },
          handleUpdateValue(value) {
            $message.info(value);
          },
          generalOptions,generalKey,
          promptCancelClick,
        }
      },
})

</script>

<template>
  <n-card
      class="header-model-card"
      content-style="padding: 1rem;"
      closable
      @close="handleClose"
  >
    <template #header>
      偏好设置
      <n-space>
        <n-button text @click="changeOptionKey('preference')">个人信息</n-button>
        <n-button text @click="changeOptionKey('privacy')">隐私</n-button>
        <n-button text @click="changeOptionKey('settings')">设置</n-button>
      </n-space>
    </template>
    <template #default>
      <n-layout has-sider border="border">
        <n-layout-content style="padding: 1rem">
<!--          个人资料-->
          <n-flex v-show="showSwitchCard('preference')" vertical>
            <n-space justify="space-between" >
              <n-space vertical style="width: 10rem;">
                <n-form ref="formRef" :model="formValue" :rules="rules" label-placement="left" label-width="5rem"
                        style="border: 1px solid black; width: 170%; padding: 1rem; border-radius: 1rem">
                  <n-form-item label="用户名" path="username">
                    <n-input v-model:value="formValue.username" placeholder="输入用户名"/>
                  </n-form-item>
                  <n-form-item label="性别&nbsp;" path="sex">
                    <n-input v-model:value="formValue.sex" placeholder="输入性别"/>
                  </n-form-item>
                  <n-form-item label="生日&nbsp;" path="birthday">
                    <n-date-picker v-model:value="formValue.birthday" type="date" placeholder="选择时间" />
                  </n-form-item>
                  <n-form-item label="简介&nbsp;" path="signature">
                    <n-input type="textarea" v-model:value="formValue.signature" placeholder="输入简介"/>
                  </n-form-item>
                </n-form>
              </n-space>
              <n-space vertical align="center" >
                <n-avatar
                    round
                    :size="121"
                    :src="formValue.userImg"
                />
                <n-upload :custom-request="customRequest">
                  <n-button text>点击上传头像</n-button>
                </n-upload>
              </n-space>
            </n-space>
          </n-flex>
<!--          隐私设置-->
          <n-flex v-show="showSwitchCard('privacy')">
            <n-form
                style="padding-left:6rem"
                label-placement="left"
            >
              <n-form-item label="邮箱">
                <n-space vertical >
                  <n-space justify="space-between">
                    <n-text type="info">adsad</n-text>
                    <n-button text>点击修改</n-button>
                  </n-space>
                  <n-space justify="space-between">
                    <n-input  disabled/>
                    <n-button type="info" disabled >验证码</n-button>
                  </n-space>
                </n-space>
              </n-form-item>
              <n-form-item label="电话">
                <n-space vertical>
                  <n-space justify="space-between">
                    <n-text type="info">adsad</n-text>
                    <n-button text>点击修改</n-button>
                  </n-space>
                  <n-space>
                    <n-input disabled/>
                    <n-button type="info" :disabled='false' @click="runTime">验证码</n-button>
                  </n-space>
                </n-space>
              </n-form-item>
              <n-form-item label="地址">
                <n-space vertical>
                  <n-space justify="end">
                    <n-button text>点击修改</n-button>
                  </n-space>
                  <n-input
                      type="textarea"
                      style="width: 16rem"
                      disabled value="重庆市"
                  ></n-input>
                </n-space>
              </n-form-item>
            </n-form>
          </n-flex>
<!--          系统设置-->
          <n-flex vertical v-show="showSwitchCard('settings')">
            <n-space>
              <n-text>中英文切换</n-text>
              <n-switch
                  checked-value="en"
                  unchecked-value="zh"
                  @update:value="handleUpdateValue"
              >
                <template #checked>
                  英文
                </template>
                <template #unchecked>
                  中文
                </template>
              </n-switch>
            </n-space>
            <n-space>
              <n-form-item label="主题切换" path="multipleSelectValue" label-placement="left">
                <n-select
                    style="width: 12rem"
                    v-model:value="generalKey"
                    placeholder="Select"
                    :options="generalOptions"
                />
              </n-form-item>
            </n-space>
            <n-divider style="margin: 0">账户操作</n-divider>

              <n-text>关于账户:</n-text>
              <n-space style="width: 100%" vertical>
                <n-space justify="space-evenly">
                  <n-icon>i</n-icon>
                  <n-icon>i</n-icon>
                  <n-icon>i</n-icon>
                </n-space>
                <n-space justify="center">
                  <n-button type="info" @click="promptCancelClick">注销账户</n-button>
                </n-space>
              </n-space>

          </n-flex>
        </n-layout-content>
      </n-layout>
    </template>
    <template #action>
      <n-space justify="space-evenly">
        <n-button type="info" @click="handleClose">取消编辑</n-button>
        <n-button type="info" @click="userCardClick">确认</n-button>
      </n-space>
    </template>
  </n-card>
</template>

<style lang="scss" scoped>
.header-model-card{
  padding: 0;
  width: 36rem;
  min-height: 21rem;
}
</style>
